﻿Imports System.Net
Imports System.Threading.Tasks
Imports System.Security.Cryptography
Imports System.Text
Imports System.Xml
Imports System.Security.Cryptography.Xml

Module m_Globals
    Public WithEvents SockGlobal As Connections
    Public ip As String
    Public port As Integer
    Public username As String
    Public nickname As String
    Public password As String
    Public auto_login As Boolean

    Public gSeparator

    'Local User
    Public localUID As String
    Public localNick As String

    Public ReadOnly desKey() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
    Public ReadOnly desVector() As Byte = {16, 1, 3, 24, 5, 13, 8, 4}
    Private tdes As New cTripleDES(desKey, desVector)

    Public Function MinDate(ByVal strDate As String) As String
        Dim dParse As Date
        Date.TryParse(strDate, dParse)

        If dParse <= Date.MinValue Then
            Return "0000-00-00 00:00:00"
        Else
            Return String.Format("{0:yyyy-MM-dd HH:mm:ss}", dParse)
        End If

    End Function

    Public Function TextToByte(ByVal text As String)
        Return Encoding.Unicode.GetBytes(text)
    End Function

    Public Function ByteToText(ByVal bytes() As Byte)
        Return Encoding.Unicode.GetString(bytes)
    End Function

    Public Function isStrEmpty(ByVal textArgs() As String)
        For i As Integer = 0 To textArgs.Length - 1
            If textArgs(i).Length <= 0 Then
                Return False
            End If
        Next
        Return True
    End Function

    ''''' MASTER KEYWORD PROCEDURE
    Public Function get_separator()
        Dim query As String = "SELECT char_pemisah FROM tb_option"
        Return mysql_query(query, 0)
    End Function

    Public Function isGridFilled(ByVal grid As DevExpress.XtraGrid.Views.Grid.GridView)
        For i As Integer = 0 To grid.RowCount - 1
            For j As Integer = 0 To 1
                If grid.GetRowCellValue(i, grid.Columns.Item(j)).ToString.Equals("") Then
                    Return False
                End If
            Next
        Next
        Return True
    End Function

    Public Function isKeywordExists(ByVal id_operasi As Long, ByVal keyword As String)
        Dim data As DataTable = mysql_query(String.Format("SELECT * FROM tb_operasi,tb_host WHERE tb_host.id_host = tb_operasi.id_host AND tb_host.is_local = '1' AND tb_operasi.keyword = '{0}' AND tb_operasi.id_operasi <> '{1}'", keyword, id_operasi))

        If data.Rows.Count > 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    ''''' FOR CLIENT CONFIGURATION STORE
    Public Function reconfig_database(db_host As String, db_port As String, db_user As String, db_password As String, db_name As String)
        Return New Object() {db_host, db_port, db_user, db_password, db_name}
    End Function

    Public Function reconfig_server(server_host As String, server_port As String, login_user As String, login_password As String, auto_connect As String)
        Return New Object() {server_host, server_port, login_user, login_password, auto_connect}
    End Function


    Public Sub client_write_configuration()
        Dim path As String = My.Application.Info.DirectoryPath.ToString & "\client.xml"
        Dim xml_writer As New XmlTextWriter(path, System.Text.Encoding.UTF8)
        Dim xmldoc As New XmlDocument()

        ' Encryptor
        Dim sharedkey As New TripleDESCryptoServiceProvider()
        Dim md5 As New MD5CryptoServiceProvider()
        Dim ed As New EncryptedData()
        Dim exml As EncryptedXml
        Dim encryptElement As XmlElement
        Dim encryptXML As Byte()

        xml_writer.WriteStartDocument(True)
        xml_writer.Formatting = Formatting.Indented
        xml_writer.Indentation = 2
        xml_writer.WriteStartElement("Configuration")
        xml_writer.WriteStartAttribute("version")
        xml_writer.WriteString("1.0")
        xml_writer.WriteEndAttribute()

        xml_writer.WriteStartElement("Application")
        xml_writer.WriteStartAttribute("remember")
        xml_writer.WriteString("false")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("username")
        xml_writer.WriteString("")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteEndElement()

        xml_writer.WriteStartElement("Server")
        xml_writer.WriteStartAttribute("user")
        xml_writer.WriteString("")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("pass")
        xml_writer.WriteString("")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("auto_login")
        xml_writer.WriteString("0")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("server_host")
        xml_writer.WriteString("localhost")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("server_port")
        xml_writer.WriteString("7777")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteEndElement()

        xml_writer.WriteStartElement("Database")
        xml_writer.WriteStartAttribute("host")
        xml_writer.WriteString("localhost")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("port")
        xml_writer.WriteString("3306")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("username")
        xml_writer.WriteString("root")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("password")
        xml_writer.WriteString("")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteStartAttribute("database")
        xml_writer.WriteString("db_mclient")
        xml_writer.WriteEndAttribute()
        xml_writer.WriteEndElement()

        xml_writer.WriteEndElement()
        xml_writer.WriteEndDocument()
        xml_writer.Close()

        xmldoc.Load(path)


        sharedkey.Key = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes("PM0C9988HAX7585"))

        exml = New EncryptedXml(xmldoc)
        encryptElement = CType(xmldoc.SelectSingleNode("/Configuration"), XmlElement)
        encryptXML = exml.EncryptData(encryptElement, sharedkey, False)

        ed.Type = EncryptedXml.XmlEncElementUrl
        ed.EncryptionMethod = New EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)
        ed.CipherData = New CipherData()
        ed.CipherData.CipherValue = encryptXML

        EncryptedXml.ReplaceElement(encryptElement, ed, False)

        xmldoc.Save(path)
    End Sub

    Public Sub client_update_configuration(ByVal Application() As Object, ByVal Server() As Object, ByVal Database() As Object)
        Try
            Dim path As String = My.Application.Info.DirectoryPath.ToString & "\client.xml"

            Dim sharedkey As New TripleDESCryptoServiceProvider()
            Dim md5 As New MD5CryptoServiceProvider()
            Dim xmlDocument As New XmlDocument()
            Dim ed As New EncryptedData()
            Dim encryptedXML As New EncryptedXml()
            Dim xmlElement As XmlElement
            Dim decryptedXML As Byte()

            sharedkey.Key = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes("PM0C9988HAX7585"))

            xmlDocument.Load(path)
            xmlElement = CType(xmlDocument.GetElementsByTagName("EncryptedData")(0), XmlElement)
            ed.LoadXml(xmlElement)

            decryptedXML = encryptedXML.DecryptData(ed, sharedkey)
            encryptedXML.ReplaceData(xmlElement, decryptedXML)

            Dim xmlnode As XmlNodeList
            xmlnode = xmlDocument.GetElementsByTagName("Configuration")

            ' Load Server Config
            If IsArray(Server) And Server.Length = 5 Then
                xmlnode(0).ChildNodes(1).Attributes.ItemOf("server_host").InnerText = Server(0)
                xmlnode(0).ChildNodes(1).Attributes.ItemOf("server_port").InnerText = Server(1)
                xmlnode(0).ChildNodes(1).Attributes.ItemOf("user").InnerText = Server(2)
                xmlnode(0).ChildNodes(1).Attributes.ItemOf("pass").InnerText = Server(3)
                xmlnode(0).ChildNodes(1).Attributes.ItemOf("auto_login").InnerText = LCase(Server(4))
            End If

            ' Load Database Config
            If IsArray(Database) And Database.Length = 5 Then
                xmlnode(0).ChildNodes(2).Attributes.ItemOf("host").InnerText = Database(0)
                xmlnode(0).ChildNodes(2).Attributes.ItemOf("port").InnerText = Database(1)
                xmlnode(0).ChildNodes(2).Attributes.ItemOf("username").InnerText = Database(2)
                xmlnode(0).ChildNodes(2).Attributes.ItemOf("password").InnerText = Database(3)
                xmlnode(0).ChildNodes(2).Attributes.ItemOf("database").InnerText = Database(4)
            End If

            encryptedXML = New EncryptedXml(xmlDocument)
            xmlElement = CType(xmlDocument.SelectSingleNode("/Configuration"), XmlElement)
            decryptedXML = encryptedXML.EncryptData(xmlElement, sharedkey, False)

            ed.Type = encryptedXML.XmlEncElementUrl
            ed.EncryptionMethod = New EncryptionMethod(encryptedXML.XmlEncTripleDESUrl)
            ed.CipherData = New CipherData()
            ed.CipherData.CipherValue = decryptedXML

            encryptedXML.ReplaceElement(xmlElement, ed, False)

            xmlDocument.Save(path)
        Catch ex As Exception

        End Try
    End Sub

    Public Sub client_read_configuration()
        Try
            Dim path As String = My.Application.Info.DirectoryPath.ToString & "\client.xml"

            Dim sharedkey As New TripleDESCryptoServiceProvider()
            Dim md5 As New MD5CryptoServiceProvider()
            Dim encryptedDoc As New XmlDocument()
            Dim ed As New EncryptedData()
            Dim encryptXML As New EncryptedXml()
            Dim EncryptedElement As XmlElement
            Dim decryptedXML As Byte()

            sharedkey.Key = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes("PM0C9988HAX7585"))

            encryptedDoc.Load(path)
            EncryptedElement = CType(encryptedDoc.GetElementsByTagName("EncryptedData")(0), XmlElement)
            ed.LoadXml(EncryptedElement)

            decryptedXML = encryptXML.DecryptData(ed, sharedkey)
            encryptXML.ReplaceData(EncryptedElement, decryptedXML)

            Dim xmlnode As XmlNodeList
            xmlnode = encryptedDoc.GetElementsByTagName("Configuration")

            ' Load Server Config
            ip = xmlnode(0).ChildNodes(1).Attributes.ItemOf("server_host").InnerText
            port = Convert.ToInt32(xmlnode(0).ChildNodes(1).Attributes.ItemOf("server_port").InnerText)
            username = xmlnode(0).ChildNodes(1).Attributes.ItemOf("user").InnerText
            password = xmlnode(0).ChildNodes(1).Attributes.ItemOf("pass").InnerText
            auto_login = XmlConvert.ToBoolean(xmlnode(0).ChildNodes(1).Attributes.ItemOf("auto_login").InnerText)

            ' Load Database Config
            dbHost = xmlnode(0).ChildNodes(2).Attributes.ItemOf("host").InnerText
            dbPort = Convert.ToInt32(xmlnode(0).ChildNodes(2).Attributes.ItemOf("port").InnerText)
            dbUser = xmlnode(0).ChildNodes(2).Attributes.ItemOf("username").InnerText
            dbPass = xmlnode(0).ChildNodes(2).Attributes.ItemOf("password").InnerText
            dbName = xmlnode(0).ChildNodes(2).Attributes.ItemOf("database").InnerText
        Catch ex As Exception
            client_write_configuration()
        End Try
    End Sub
End Module
